//
//  UITableView+Line.swift
//  HeadlineNews
//
//  Created by han on 2019/7/19.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

extension UITableView {
    /// 给Section背景添加圆角
    ///
    /// 给每个cell设置backgroundView，给每个cell添加下划线
    func addSectionCornerForCell(_ cell: UITableViewCell,
                                 radius: CGFloat,
                                 at indexPath: IndexPath,
                                 fillColor: UIColor = UIColor.white,
                                 selectedColor: UIColor? = UIColor.red,
                                 inset: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10),
                                 bottomLine: Bool = true) {
        guard indexPath.section + 1 <= self.numberOfSections else { return }
        let rowsNumber = self.numberOfRows(inSection: indexPath.section)
        let row = indexPath.row
        guard row + 1 <= rowsNumber else { return }
        let leftPadding: CGFloat = 15.0
        let rightPadding: CGFloat = 10.0
        
        var addLine = true;
        let rect = cell.bounds.inset(by: inset)
        let shapeLayer = CAShapeLayer()
        var path = UIBezierPath(rect: rect)
        
        if row == 0 && (row == (rowsNumber - 1)){
            path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight, .bottomLeft, .bottomRight], cornerRadii: CGSize(width: radius, height: radius))
            addLine = false
        } else if row == 0 {
            path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: radius, height: radius))
        } else if row == (rowsNumber - 1) {
            path = UIBezierPath(roundedRect: rect, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: radius, height: radius))
            addLine = false
        }
        
        shapeLayer.path = path.cgPath
        shapeLayer.fillColor = fillColor.cgColor
        
        if bottomLine && addLine {
            let lineLayer = CALayer()
            let lineHeight = 1.0 / UIScreen.main.scale
            lineLayer.frame = CGRect(x: rect.minX + leftPadding, y: rect.height - lineHeight, width: rect.width - leftPadding - rightPadding , height: lineHeight)
            lineLayer.backgroundColor = self.separatorColor?.cgColor
            shapeLayer.addSublayer(lineLayer)
        }
        
        let back = UIView(frame: rect)
        back.layer.insertSublayer(shapeLayer, at: 0)
        back.backgroundColor = UIColor.clear
        cell.backgroundView = back
        
        guard let selectedColor = selectedColor else { return }
        
        let selected = UIView(frame: rect)
        let layer: CAShapeLayer = CAShapeLayer()
        layer.path = path.cgPath
        layer.fillColor = selectedColor.cgColor
        selected.backgroundColor = UIColor.clear
        selected.layer.insertSublayer(layer, at: 0)
        cell.selectedBackgroundView = selected
        
    }
    
    /// 给cell添加bottomline
    ///
    /// 通过给cell设置backgroundView，添加一个layer，然后添加一个lineLayer
    func addBottomLine(for cell: UITableViewCell,
                       at indexPath: IndexPath,
                       lineColor: UIColor?,
                       leftSpace: CGFloat = 15,
                       rightSpace: CGFloat = 15,
                       sectionLine: Bool = true) {
        guard indexPath.section + 1 <= self.numberOfSections else { return }
        let rowsNumber = self.numberOfRows(inSection: indexPath.section)
        let row = indexPath.row
        guard row + 1 <= rowsNumber else { return }
        
        var color = UIColor.black.withAlphaComponent(0.5)
        if let lineColor = lineColor {
            color = lineColor
        } else {
            if let separatorColor = self.separatorColor {
                color = separatorColor
            }
        }
        
        let rect = cell.bounds.insetBy(dx: 0, dy: 0)
        let shapeLayer = CAShapeLayer()
        let path = UIBezierPath(rect: rect)
        shapeLayer.path = path.cgPath
        if cell.backgroundColor != nil {
            shapeLayer.fillColor = cell.backgroundColor?.cgColor
        } else {
            shapeLayer.fillColor = UIColor.white.cgColor
        }
        
        if row == 0 && (row == (rowsNumber - 1)){
            if sectionLine {
                addLine(of: shapeLayer, isUp: true, rect: rect, lineColor: color)
                addLine(of: shapeLayer, isUp: false, leftSpace: 0, rightSpace: 0, rect: rect, lineColor: color)
            } else {
                addLine(of: shapeLayer, isUp: false, leftSpace: leftSpace, rightSpace: rightSpace, rect: rect, lineColor: color)
            }
        } else if row == 0 {
            if sectionLine {
                addLine(of: shapeLayer, isUp: true, rect: rect, lineColor: color)
            }
            addLine(of: shapeLayer, isUp: false, leftSpace: leftSpace, rightSpace: rightSpace, rect: rect, lineColor: color)
            
        } else if row == (rowsNumber - 1) {
            if sectionLine {
                addLine(of: shapeLayer, isUp: false, leftSpace: 0, rightSpace: 0, rect: rect, lineColor: color)
            } else {
                addLine(of: shapeLayer, isUp: false, leftSpace: leftSpace, rightSpace: rightSpace, rect: rect, lineColor: color)
            }
        } else {
            addLine(of: shapeLayer, isUp: false, leftSpace: leftSpace, rightSpace: rightSpace, rect: rect, lineColor: color)
        }
        
        let back = UIView(frame: rect)
        back.layer.insertSublayer(shapeLayer, at: 0)
        back.backgroundColor = UIColor.clear
        cell.backgroundView = back
    }
    
    private func addLine(of layer: CALayer, isUp: Bool, leftSpace: CGFloat = 0, rightSpace: CGFloat = 0, rect: CGRect, lineColor: UIColor) {
        let lineLayer = CALayer()
        let lineHeight = 1.0 / UIScreen.main.scale
        let lineTop = isUp ? 0 : rect.height - lineHeight
        lineLayer.frame = CGRect(x: rect.minX + leftSpace, y: lineTop, width: rect.width - leftSpace - rightSpace, height: lineHeight)
        lineLayer.backgroundColor = lineColor.cgColor
        layer.insertSublayer(lineLayer, at: 0)
    }
}

extension UIView {
    // 给view添加圆角
    func roundCorners(rect: CGRect, corners: UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
    
    func noCornerMask() {
        layer.mask = nil
    }
}
